if(!window.xflib || !window.xflib.client) window.xflib = { client: {} }

xflib.client.CategoryService = class CategoryService {

    constructor(storage) {
        this.storage = storage;
    }

    async create(categoryCode, categoryName) {
        if(categoryCode && categoryName){
            return this.storage.instance.get("categories").then((data)=>{
                const categories = data.categories || {};
                if(Object.keys(categories).includes(categoryCode) && categories[categoryCode] === categoryName){
                    return Promise.reject("category already exists.");
                }
                return this.storage.instance.set({categories: {...categories, [categoryCode]: categoryName}});
            }).catch((error)=>{
                return Promise.reject(error.message);
            });
        }
        return Promise.reject("cannot null or empty categories.");
    }

    async update(categoryOldCode, categoryCode, categoryName) {
        if(categoryCode && categoryName){
            return this.storage.instance.get("categories").then((data)=>{
                const categories = data.categories || {};
                if(categories && categories[categoryOldCode]){
                    delete categories[categoryOldCode];
                }
                return this.storage.instance.set({categories: {...categories, [categoryCode]: categoryName}});
            }).catch((error)=>{
                return Promise.reject(error.message);
            });
        }
        return Promise.reject("cannot null or empty categories.");
    }

    async delete(categoryCodes) {
        if(categoryCodes){
            return this.storage.instance.get("categories").then((data)=>{
                const categories = data.categories || {};
                this.toArray(categoryCodes).forEach((categoryCode)=>{
                    if(categories && categories[categoryCode]){
                        delete categories[categoryCode];   
                    }
                });
                return this.storage.instance.set({categories: categories});
            }).catch((error)=>{
                return Promise.reject(error.message);
            });
        }
        return Promise.reject("cannot null or empty category codes.");
    }

    async clear() {
        return this.storage.instance.clear("categories");
    }

    async queryByCategoryCodes(categoryCodes="categories") {
        return this.storage.instance.get(categoryCodes).then((data)=>{
            return data.categories;
        });
    }
    
    toArray(value) {
        if (value === null) return [];
        if (Array.isArray(value)) return value;
        return [value];
    }
} 